package com.neusoft.bizcore.activiti.repository.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.activiti.enums.FormType;
import com.neusoft.bizcore.activiti.model.ProcessForm;
import com.neusoft.bizcore.activiti.model.QProcessForm;
import com.neusoft.bizcore.activiti.repository.CustomizedProcessFormRepository;
import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedProcessFormRepositoryImpl extends AbstractRepository implements CustomizedProcessFormRepository {

    @Override
    public List<ProcessForm> index(final Searchable searchable) {
        final QProcessForm qProcessForm = QProcessForm.processForm;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<ProcessForm> query = this.query().selectFrom(qProcessForm);
        query.where(where).distinct();
        return query.fetch();
    }

    @Override
    public Page<ProcessForm> search(final Pageable pageable, final Searchable searchable) {
        final QProcessForm qProcessForm = QProcessForm.processForm;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<ProcessForm> query = this.query().selectFrom(qProcessForm);
        query.where(where);
        return super.search(query, pageable);
    }

    @Override
    protected Class<?> getModelClass() {
        return ProcessForm.class;
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QProcessForm qProcessForm = QProcessForm.processForm;

        // 表单名称
        if (!StringUtils.isEmpty(searchable.getStrValue("name"))) {
            where.and(super.containsStr(qProcessForm.name, searchable, "name"));
        }

        // 分类
        if (!StringUtils.isEmpty(searchable.getStrValue("processKey"))) {
            where.and(super.equalsStr(qProcessForm.process.any().code, searchable, "processKey"));
        }

        // 表单类型
        if (!StringUtils.isEmpty(searchable.getStrValue("type"))) {
            where.and(super.equalsEnum(qProcessForm.type, searchable, "type",
                    value -> FormType.valueOf(value)));
        }

        // 工单类型
        if (!StringUtils.isEmpty(searchable.getStrValue("workType"))) {
            where.and(super.equalsStr(qProcessForm.workType, searchable, "workType"));
        }
        return where;
    }
}
